package com.jy.wms.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.joyi.gate.comm.SessionInfo;
import com.joyi.gate.safety.vo.UserInfo;
import com.jy.wms.common.UUIDUtils;
import com.jy.wms.common.annotions.BaseServiceDescribe;
import com.jy.wms.common.base.*;
import com.jy.wms.dao.WmsPackingMapper;
import com.jy.wms.pojo.*;
import net.sf.json.JSONObject;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.util.PoiPublicUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
    * @ClassName: WmsPackingService.java
    * @Description: TODO(这里用一句话描述这个类的作用)
    * @Author JaneLiu
    * @Date Wed Sep 06 10:34:42 CST 2017
    */

@Service
public class WmsPackingService extends BaseService<WmsPackingMapper,WmsPacking> {

     /**
     * 新增包装
     * @param wmsPacking
     * @return int
     */
     @BaseServiceDescribe(moduleName = "包装管理",btnName = "新增包装")
     @Transactional
    public void baseInsert( WmsPacking wmsPacking) throws Exception{
         List<WmsPacking> wmsPackingList = new ArrayList<>();
        Integer flaga2=0;
         Integer flaga1 = 0;
         List<WmsPacking> arraymx = wmsPacking.getList();//取明细集合
         for (WmsPacking packing : arraymx) {
             if (packing.equals("0")) {
                 //主单位验证非空
                 verification(packing, "主单位");
             } else if (packing.equals("2")) {
                 //箱验证非空
                 verification(packing, "箱");
             } else if (packing.equals("3")) {
                 //托盘TH值验证非空
                 verification3(packing, "托盘");
             }
             packing.setMxid(UUIDUtils.uuid());
             packing.setCkid(wmsPacking.getCkid());
             packing.setSsbzid(wmsPacking.getId());
             flaga1 = dao.baseInsert_mx(packing);//保存明细
             SysDictionary sysDictionary = selectType(packing, "wms_packing_detailed_bzlx");//查字典显示show_的字段
             packing.setShow_bzlx(sysDictionary.getD_name());
             if (flaga1 > 0) {
                 flaga2++;
                 wmsPackingList.add(packing);
             } else {
                 rollBack(wmsPackingList);
                 throw new ServiceException("新增包装明细信息失败");
            }
         }
         if (flaga2 == wmsPacking.getList().size()) {
             Integer flaga = dao.baseInsert(wmsPacking);//保存包装
             if (flaga > 0) {
                 throw new SucessException("新增包装信息成功");
             } else {
                 rollBack(wmsPackingList);
                 throw new ServiceException("新增包装信息失败");
             }
        }else{
             rollBack(wmsPackingList);
             throw new ServiceException("新增包装明细信息失败");
        }
    }

    /**
     * 验证
     *
     * @param packing
     * @param mx
     * @throws Exception
     */
    public void verification(WmsPacking packing, String mx) throws Exception {
        if (!"".equals(packing.getC()) && packing.getC() != null) {

        } else {
            throw new ServiceException("新增包装明细" + mx + "长度不可为空");
        }
        if (!"".equals(packing.getK()) && packing.getK() != null) {

        } else {
            throw new ServiceException("新增包装明细" + mx + "宽度不可为空");
        }
        if (!"".equals(packing.getG()) && packing.getG() != null) {

        } else {
            throw new ServiceException("新增包装明细" + mx + "高度不可为空");
        }
        if (!"".equals(packing.getZdwsl()) && packing.getZdwsl() != null) {

        } else {
            throw new ServiceException("新增包装明细" + mx + "主单位数量不可为空");
        }
    }

    /**
     * 验证
     *
     * @param packing
     * @param mx
     * @throws Exception
     */
    public void verification3(WmsPacking packing, String mx) throws Exception {
        if (!"".equals(packing.getTh()) && packing.getTh() != null) {

        } else {
            throw new ServiceException("新增包装明细" + mx + "TH值不可为空");
        }
    }


    /**
     * 包装添加回滚
     *
     * @param wmsPackingList
     */
    public void rollBack(List<WmsPacking> wmsPackingList) throws Exception {
        for (WmsPacking wmsPacking : wmsPackingList) {
            Integer j = dao.deleteMx(wmsPacking.getMxid());
            if (j <= 0) {
                throw new ServiceException("新增包装明细回滚失败");
            }
        }
    }
    /**
    * 分页查询
    * @param entity 实体
    * @return Page<WmsPacking>
    */
    @BaseServiceDescribe(moduleName = "包装管理",btnName = "分页查询包装")
    public Page<WmsPacking> baseSelectPage(WmsPacking entity) throws ServiceException {
        try{
            PageHelper.startPage(entity.getPage(),entity.getRows());
            return (Page<WmsPacking>)dao.baseSelectPage(entity);
        }catch(Exception e){
            throw  new ServiceException("查询包装信息失败",e);
        }
    }
   /**
    * 修改查询（根据主键ID查询）
    * @param id 主键ID
    * @return WmsPacking
    */
    public WmsPacking baseSelectByPrimaryKey(String id){
        List<WmsPacking> list=dao.baseSelectByPrimaryKey_mx(id);//查询明细id
        WmsPacking wmsPacking=dao.baseSelectByPrimaryKey(id);//查询包装id
        wmsPacking.setList(list);
        return wmsPacking;
    }
   /**
    *修改包装及明细
    * @param wmsPacking 主键ID列表
    * @return int
    */
   @BaseServiceDescribe(moduleName = "包装管理",btnName = "编辑包装")
   public void baseUpdateByPrimaryKeySelectivexg(WmsPacking wmsPacking) throws Exception{
       Integer flaga2=0;
       Integer flaga= dao.baseUpdateByPrimaryKeySelective(wmsPacking);//保存包装
        if(flaga>0){
            List<WmsPacking> arraymx =  wmsPacking.getList();//取明细集合
            for (WmsPacking packing:arraymx){
                flaga2=dao.baseUpdateByPrimaryKeySelective_mx(packing);//保存明细
                SysDictionary sysDictionary=selectType(packing,"wms_packing_detailed_bzlx");//查字典显示show_的字段
                packing.setShow_bzlx(sysDictionary.getD_name());
                if(flaga2<0){
                    throw new ServiceException("编辑包装明细信息失败");
                }
            }
            throw new SucessException("编辑包装信息成功");
        }else {
            throw new ServiceException("编辑包装信息失败");
        }
   }
        /**
         * 根据货主Id查询
         * @param sshzid 实体
         * @return List<WmsPacking>
         */
        public List<WmsPacking>  baseSelectBySshzid(String mc,String sshzid){
            return dao.baseSelectBySshzid(mc,sshzid);
        }

    /**
     *修改（根据主键ID修改绑定货品ID）

     * @return int
     */
   public Integer baseUpdateByPrimaryKeySelective( WmsPacking entity) {
        return dao.baseUpdateByPrimaryKeySelective(entity);
    }
    //添加去重
    public WmsPacking searchAdd(String bzmc,String ckid,String sshzid){
        return dao.searchAdd(bzmc,ckid,sshzid);
    }
    //修改去重
    public WmsPacking searchAdds(String bzmc,String id,String ckid,String sshzid){
        return dao.searchAdds(bzmc,id,ckid,sshzid);
    }
    //查字典
    public SysDictionary selectType(WmsPacking wmsPacking,String type){
        return dao.selectType(wmsPacking,type);
    }
    //查货主名
    public WmsPacking addSearch(String id)  {
        return dao.addSearch(id);
    }
    /**
     *  堆码中添加去重库位高度
     * @param kwgd
     * @param ckid
     * @param hzid
     * @param bzid
     * @return
     */

    public WmsStacking searchStackAdd(Double kwgd, String ckid, String hzid, String bzid) {
        return dao.searchStackAdd(kwgd, ckid, hzid, bzid);
    }
    /**
     * 堆码中编辑去重库位高度
     * @param id
     * @param kwgd
     * @param ckid
     * @param hzid
     * @return
     */
    public WmsStacking searchStackAdds(String id, String bzid, Double kwgd, String ckid, String hzid) {
        return dao.searchStackAdds(id, bzid, kwgd, ckid, hzid);
    }


    @BaseServiceDescribe(moduleName = "包装管理",btnName = "修改堆码")
    @Transactional
    public void editStacking( WmsStacking wmsStacking) throws Exception{
        if (!"".equals(wmsStacking.getTh()) && wmsStacking.getTh() != null) {
        } else {
            wmsStacking.setTh("0");
        }
        Integer flaga=dao.editStacking(wmsStacking);
        if (flaga > 0) {
            throw new SucessException("修改堆码信息成功");
        } else {
            throw new ServiceException("修改堆码信息失败");
        }
    }

    /**
     * 查看单个堆码信息(编辑前的查询用)
     * @param id
     * @return
     */
    public WmsStacking getWmsStacking(String id){
        return dao.getWmsStacking(id);
    }

    @BaseServiceDescribe(moduleName = "包装管理",btnName = "新增堆码")
    @Transactional
    public void insertStacking( WmsStacking wmsStacking) throws Exception{
        wmsStacking.setId(UUIDUtils.uuid());
        if (!"".equals(wmsStacking.getTh()) && wmsStacking.getTh() != null) {
        } else {
            wmsStacking.setTh("0");
        }
        Integer flaga=dao.insertStacking(wmsStacking);
        if (flaga > 0) {
            throw new SucessException("新增堆码信息成功");
        } else {
            throw new ServiceException("新增堆码信息失败");
        }
    }
    //删除
    @BaseServiceDescribe(moduleName = "堆码管理",btnName = "删除堆码")
    public void deleteStacking( List<String> idList ) throws Exception{
        Integer i = dao.deleteStacking( idList );
        if(i>0){
            throw new SucessException("删除堆码成功");
        }else{
            throw new ServiceException("删除堆码失败");
        }
    }
    /**
     * 分页查询堆码列表
     * @param entity
     * @return
     */
    @BaseServiceDescribe(moduleName = "堆码管理",btnName = "分页查询堆码")
    public Page<WmsStacking> getListStacking(WmsStacking entity) throws ServiceException {
        try{
            PageHelper.startPage(entity.getPage(),entity.getRows());
            return (Page<WmsStacking>)dao.getListStacking(entity);
        }catch(Exception e){
            throw  new ServiceException("查询堆码信息失败",e);
        }
    }

    /**
     * 导入包装明细信息
     * @param session
     * @param filepath
     * @throws ServiceException
     * @throws SucessException
     * @throws Exception
     */
    @BaseServiceDescribe(moduleName = "导入包装明细信息", btnName = "导入包装明细信息")
    @Transactional
    public void importPackingmxExcle(HttpSession session, String  filepath) throws Exception {
        ImportParams params = new ImportParams();
        params.setNeedSave(false);
        params.setTitleRows(0);
        params.setHeadRows(1);
        params.setDataHanlder(new WmsPackingMxMapImportHanlder());
        JSONObject jb = JSONObject.fromObject(filepath);
        URL url = new URL((String) jb.get("filepath"));
        URLConnection conn = url.openConnection();
        List<Map<String, Object>> result = ExcelImportUtil.importExcel(
                conn.getInputStream(),
                //new File(PoiPublicUtil.getWebRootPath("import/包装明细导入模版.xls")),
                Map.class, params);
        System.out.println("result:"+result);
        UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
        List<SysHz> hz = (List<SysHz>) session.getAttribute(BaseSessionInfo.SessionConsignor);
        //仓库id
        String ckid = String.valueOf(userinfo.getUser().getOrgId().get(0));
        //货主id
        String hzid = null;
        if (hz.size() > 0) {
            hzid = hz.get(0).getHzid();
        }
        for (int i = 0; i < result.size(); i++) {
            result.get(i).put("num", i + 2);
        }
        //表格去重
        removeDuplicate(result);
        //数据库去重
        removeDataDuplicate(result, hzid, ckid);
        //添加数据
        for(int i=0;i<result.size();i++){
             WmsPacking packing = dao.getBzmx(result.get(i).get("bzmc").toString(),hzid,ckid);
             if(packing!=null){
                 packing.setMxid(UUIDUtils.uuid());
                 packing.setSsbzid(packing.getId());
                 String bzlx = bzlx("", result.get(i).get("bzlx").toString());
                 packing.setBzlx(bzlx);
                 int idx = result.get(i).get("sl").toString().lastIndexOf(".");//查找小数点的位置
                 String sl = result.get(i).get("sl").toString().substring(0, idx);//截取从字符串开始到小数点位置的字符串，就是整数部分
                 packing.setZdwsl(sl);
                 packing.setMs(result.get(i).get("mxbzms").toString());
                 String clm = bl(result.get(i).get("clm").toString());
                 packing.setC(clm);
                 String klm = bl(result.get(i).get("klm").toString());
                 packing.setK(klm);
                 String glm = bl(result.get(i).get("glm").toString());
                 packing.setG(glm);
                 String tj = bl(result.get(i).get("tj").toString());
                 packing.setTj(tj);
                 packing.setZl(result.get(i).get("mzlk").toString());
                 packing.setJz(result.get(i).get("jz").toString());
                 packing.setJe(result.get(i).get("je").toString());
                 if (result.get(i).get("th") != null) {
                     packing.setTh(result.get(i).get("th").toString());
                 } else {
                     packing.setTh("*");
                 }
                 packing.setCkid(ckid);
                Integer flaga= dao.baseInsert_mx(packing);//保存明细
                 if(flaga<=0){
                   throw new ServiceException("导入包装明细失败");
                 }
             }else {
                 throw new ServiceException("请先导入包装名称:"+result.get(i).get("bzmc").toString());
             }

        }
    }

    /**
     * 包装类型转换
     *
     * @param num
     * @param lx
     * @return
     * @throws Exception
     */
    public String bzlx(String num, String lx) throws Exception {
        //0主单位 1内包装 2箱 3托盘
        String bzlx = null;
        if ("主单位".equals(lx)) {
            bzlx = "0";
        } else if ("内包装".equals(lx)) {
            bzlx = "1";
        } else if ("箱".equals(lx)) {
            bzlx = "2";
        } else if ("托盘".equals(lx)) {
            bzlx = "3";
        } else {
            throw new ServiceException("第" + num + "行，包装类型：" + lx + "有误");
        }
        return bzlx;
    }

    /**
     * 保留两位小数
     *
     * @param str
     * @return
     */
    public String bl(String str) {
        Double f = Double.parseDouble(str);
        BigDecimal b = new BigDecimal(f);
        double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        str = String.valueOf(f1);
        return str;
    }
    /**
     * 包装明细报表内去重
     */
    public void removeDuplicate(List<Map<String, Object>> lis) throws ServiceException {
        //报表内不允许存在相同包装名称的情况
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < lis.size() - 1; i++) {
            for (int j = i + 1; j < lis.size(); j++) {
                if (lis.get(j).get("bzmc").equals(lis.get(i).get("bzmc"))&& lis.get(j).get("bzlx").equals(lis.get(i).get("bzlx"))) {
                    sb.append("第" + lis.get(j).get("num") + "行，包装名称:" + lis.get(j).get("bzmc").toString()+ ",包装类型:"+lis.get(j).get("bzlx").toString()+",");
                    lis.remove(j);
                    j--;
                }
            }
        }
        if (sb != null && !"".equals(sb) && sb.length() > 0) {
            throw new ServiceException("表格中" + sb + "包装明细重复，导入失败");
        }

    }

    /**
     * 包装明细数据库去重
     *
     * @param lis
     * @param hzid
     * @param ckid
     * @throws ServiceException
     */
    public void removeDataDuplicate(List<Map<String, Object>> lis, String hzid, String ckid) throws Exception {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < lis.size(); i++) {
            JSONObject jb = new JSONObject();
            String bzlx = bzlx(lis.get(i).get("num").toString(), lis.get(i).get("bzlx").toString());
            /*//0主单位 1内包装 2箱 3托盘
            String bzlx=null;
            if("主单位".equals(lis.get(i).get("bzlx").toString())){
                bzlx="0";
            }else if("内包装".equals(lis.get(i).get("bzlx").toString())){
                bzlx="1";
            }
            else if("箱".equals(lis.get(i).get("bzlx").toString())){
                bzlx="2";
            }
            else if("托盘".equals(lis.get(i).get("bzlx").toString())){
                bzlx="3";
            }else{
                throw new ServiceException("第" + lis.get(i).get("num") + "行，包装类型：" + lis.get(i).get("bzlx") + "有误");
            }*/
            //查询包装名称下的包装类型(同一货主不可重复)
            Integer e = dao.getCountByBzmc(hzid, lis.get(i).get("bzmc").toString(), ckid,bzlx);
            if (e > 0) {
                sb.append("第" + lis.get(i).get("num") + "行，包装名称:" + lis.get(i).get("bzmc") + ",包装类型:"+ lis.get(i).get("bzlx")+",");
            }
        }
        if (sb != null && !"".equals(sb) && sb.length() > 0) {
            throw new ServiceException(sb + "数据库同包装名称下,包含重复包装类型,导入失败");
        }
    }

    /**
     * 导入包装信息
     * @param session
     * @param filepath
     * @throws ServiceException
     * @throws SucessException
     * @throws Exception
     */
    @BaseServiceDescribe(moduleName = "导入包装信息", btnName = "导入包装信息")
    @Transactional
    public void importPackingExcle(HttpSession session, String  filepath) throws Exception {
        ImportParams params = new ImportParams();
        params.setNeedSave(false);
        params.setTitleRows(0);
        params.setHeadRows(1);
        params.setDataHanlder(new WmsPackingMapImportHanlder());
        JSONObject jb = JSONObject.fromObject(filepath);
        URL url = new URL((String) jb.get("filepath"));
        URLConnection conn = url.openConnection();
        List<Map<String, Object>> result = ExcelImportUtil.importExcel(
                conn.getInputStream(),
                /*new File(PoiPublicUtil.getWebRootPath("import/包装信息导入模版.xls")),*/
                Map.class, params);
        System.out.println("result:"+result);
        UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
        List<SysHz> hz = (List<SysHz>) session.getAttribute(BaseSessionInfo.SessionConsignor);
        //仓库id
        String ckid = String.valueOf(userinfo.getUser().getOrgId().get(0));
        //货主id
        String hzid = null;
        if (hz.size() > 0) {
            hzid = hz.get(0).getHzid();
        }
        for (int i = 0; i < result.size(); i++) {
            result.get(i).put("num", i + 2);
        }
        //表格去重
        removeDuplicatePack(result);
        //数据库去重
        removeDataDuplicatePack(result, hzid, ckid);
        //添加数据
        for(int i=0;i<result.size();i++){
            WmsPacking packing = new WmsPacking ();
            packing.setId(UUIDUtils.uuid());
            packing.setBzmc(result.get(i).get("bzmc").toString());
            packing.setBzms(result.get(i).get("zbzms").toString());
            packing.setFphpid("0");
            packing.setSshzid(hzid);
            packing.setCkid(ckid);
            Integer flaga= dao.baseInsert(packing);//保存包装
            if  (flaga <= 0){
                throw new ServiceException("导入包装信息失败");
            }
        }
    }

    /**
     * 包装表格内部去重
     * @param lis
     * @throws ServiceException
     */
    public void removeDuplicatePack(List<Map<String, Object>> lis) throws ServiceException {
        //报表内不允许存在相同包装名称的情况
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < lis.size() - 1; i++) {
            for (int j = i + 1; j < lis.size(); j++) {
                if (lis.get(j).get("bzmc").equals(lis.get(i).get("bzmc"))) {
                    sb.append("第" + lis.get(j).get("num") + "行，包装名称:" + lis.get(j).get("bzmc").toString()+",");
                    lis.remove(j);
                    j--;
                }
            }
        }
        if (sb != null && !"".equals(sb) && sb.length() > 0) {
            throw new ServiceException("表格中" + sb + "包装名称重复，导入失败");
        }

    }

    /**
     * 包装数据库去重
     * @param lis
     * @param hzid
     * @param ckid
     * @throws ServiceException
     */
    public void removeDataDuplicatePack(List<Map<String, Object>> lis, String hzid, String ckid) throws ServiceException {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < lis.size(); i++) {
            JSONObject jb = new JSONObject();
            //查询包装名称下的包装类型(同一货主不可重复)
            WmsPacking packing = dao.searchAdd(lis.get(i).get("bzmc").toString(),ckid,hzid);
            if (packing != null) {
                sb.append("第" + lis.get(i).get("num") + "行，包装名称:" + lis.get(i).get("bzmc")+",");
                lis.remove(i);
                i--;
            }
        }
        if (sb != null && !"".equals(sb) && sb.length() > 0) {
            throw new ServiceException(sb + "数据库包装名称重复,导入失败");
        }
    }
}
